import React, { useEffect, useState, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import ImageForm from '../../sections/forms/text2video/index';
import Image2VideoForm from '../../sections/forms/image2video/index';
// import Keyframe2VideoForm from '../../sections/forms/keyframe2video/index';

import useFormStore from 'src/context/usetypeformstore';

import api from 'api/config';
import './style.scss';

const TypeSelection = (props) => {
    const { addfake } = props;
    const [isGenerateDisabled, setIsGenerateDisabled] = useState(true);
    const { t, i18n } = useTranslation('home', { keyPrefix: 'generateleft' });

    const formRef = useRef(null);
    const state = useFormStore();
    const selectedType = state.selectedType;
    const { setModelData, setSelectedType, setFormData } = useFormStore();
    const KNOWN_PARAMS = new Set([
        'version',
        'v',
        'aspect',
        'ar',
        'turbo',
        'fast',
        'relax',
        'raw',
        'stylize',
        's',
        'chaos',
        'c',
        'weird',
        'w',
        'quality',
        'q',
    ]);

    const parsePrompt = (prompt) => {
        const result = {
            cleanPrompt: prompt,
            params: {},
        };

        // 匹配 --key 或 --key value
        const paramRegex = /--(\w+)(?:\s+((?!--)[^\s]+))?/g;
        let match;
        const matches = [];

        while ((match = paramRegex.exec(prompt)) !== null) {
            matches.push(match);
        }

        // 逆序处理，避免索引错乱
        const sortedMatches = matches.sort((a, b) => b.index - a.index);
        let cleaned = prompt;

        for (const match of sortedMatches) {
            const key = match[1].toLowerCase();

            // 只有在 KNOWN_PARAMS 中的参数才提取并从 prompt 中移除
            if (KNOWN_PARAMS.has(key)) {
                const value = match[2] !== undefined ? match[2] : true;
                result.params[key] = value;

                const fullMatch = match[0];
                cleaned =
                    cleaned.slice(0, match.index) +
                    cleaned.slice(match.index + fullMatch.length);
            }
        }

        result.cleanPrompt = cleaned.trim().replace(/\s+/g, ' ');
        return result;
    };
    async function loadModels() {
        try {
            const response = await api.get('/v1/tob/versions');

            // 将模型数据转换为适合前端使用的格式
            const modelsByType = {
                image: [],
                video: [
                    {
                        v7: '7',
                    },
                ],
            };

            // // 处理从API返回的模型数据
            modelsByType.image = response.data;
            setModelData(modelsByType);
        } catch (error) {
            console.error('加载模型选项失败:', error);
            console.error(
                'Error details:',
                error.response?.data || error.message
            );

            // // 使用默认模型数据

            const defaultModelsByType = {
                image: [{ v7: '7' }],
                video: [
                    {
                        videov7: 'Midjourney-V7',
                    },
                ],
            };

            setModelData(defaultModelsByType);
        }
    }

    const handleGenerate = async () => {
        const currentFormData = state[selectedType];
        if (selectedType === 'image') {
            const { cleanPrompt, params } = parsePrompt(
                currentFormData.prompts
            );
            //生图请求
            try {
                const response = await api.post('/v1/tob/diffusion', {
                    ...currentFormData,
                    prompts: cleanPrompt,
                });
                if (response.status === 200) {
                    //成功生成中就先触发一次重新加载
                    addfake(
                        {
                            jobId: response.data.jobId,
                            params: {
                                ...currentFormData,
                                prompts: cleanPrompt,
                            },
                            type: selectedType,
                            status: response.data.status,
                            resultUrl: [],
                        },
                        'image'
                    );
                }
            } catch (error) {}
        } else if (selectedType === 'video') {
            if (currentFormData.isLoop == 1) {
            }
            const data = {
                ...currentFormData,
                lastFrame:
                    currentFormData.isLoop == 1
                        ? ''
                        : currentFormData.lastFrame,
            };
            try {
                const response = await api.post(
                    '/v1/tob/video-diffusion',
                    data
                );

                if (response.status === 200) {
                    //成功生成中就先触发一次重新加载
                    addfake(
                        {
                            jobId: response.data.jobId,
                            params: data,
                            type: selectedType,
                            status: response.data.status,
                            resultUrl: [],
                        },
                        'video'
                    );
                }
            } catch (error) {}
        }
        //跳转到顶部
        if (document.querySelector('.video-library-list')) {
            // console.log('跳到顶部');
            document
                .querySelector('.video-library-list')
                .scrollTo({ top: 0, behavior: 'auto' });
        }
    };

    const renderForm = () => {
        switch (selectedType) {
            case 'image':
                return <ImageForm />;
            case 'video':
                return <Image2VideoForm />;

            default:
                return null;
        }
    };

    // 添加 useEffect 钩子来调用 loadModels 方法
    useEffect(() => {
        loadModels();
    }, []);

    useEffect(() => {
        checkGenerateStatus(selectedType, state[selectedType]);
    }, [selectedType, { ...state[selectedType] }]);

    // 新增方法：根据当前表单类型和内容判断生成按钮状态
    const checkGenerateStatus = (type, content) => {
        let status = false;
        switch (type) {
            case 'image':
                status = content.prompts.trim().length > 0;
                break;
            case 'video':
                status = content.firstFrame !== '';
                break;
            default:
                status = false;
        }
        setIsGenerateDisabled(!status); // 直接更新生成按钮的禁用状态
        return status;
    };

    return (
        <div className="type-selection">
            <div className="type-content">{renderForm()}</div>
            <div className="type-footer">
                <button
                    className="generate-button"
                    disabled={isGenerateDisabled}
                    onClick={handleGenerate}
                >
                    <svg
                        xmlns="http://www.w3.org/2000/svg"
                        xmlnsXlink="http://www.w3.org/1999/xlink"
                        fill="none"
                        version="1.1"
                        width="11"
                        height="12"
                        viewBox="0 0 11 12"
                    >
                        <g transform="matrix(1,0,0,-1,0,24)">
                            <path
                                d="M10.685,18.67649C10.6827,18.67765,10.6805,18.67879,10.6782,18.67991C8.51577,19.74992,6.92006,21.212699999999998,6.0999,23.5625C6.00957,23.8213,5.77257,23.9998,5.50019,24L5.49981,24C5.22743,23.9998,4.99044,23.8213,4.9001,23.5625C4.07994,21.212699999999998,2.48423,19.74992,0.321798,18.67991C0.31953,18.67879,0.317273,18.67765,0.315029,18.67649C-0.130152,18.44689,-0.130153,17.55311,0.315029,17.32351C0.317273,17.32235,0.31953,17.32121,0.321798,17.32009C2.48423,16.25009,4.07994,14.78731,4.9001,12.437494C4.99044,12.178689,5.22743,12.000165745,5.49981,12L5.50019,12C5.77257,12.000165745,6.00957,12.178689,6.0999,12.437494C6.92006,14.78731,8.51577,16.25009,10.6782,17.32009C10.6805,17.32121,10.6827,17.32235,10.685,17.32351C11.1302,17.55311,11.1302,18.44689,10.685,18.67649"
                                fillRule="evenodd"
                                fill="#FFFFFF"
                                fillOpacity="1"
                            />
                        </g>
                    </svg>
                    {selectedType === 'image'
                        ? t('generatetitle')
                        : t('generatetitle2')}
                </button>
            </div>
        </div>
    );
};

export default TypeSelection;
